<template>
  <div class="net-wan relative">
    <page-loading ref="loading"></page-loading>
    <!-- <os-entry :item="$t('network.wan.proto_label')">
      <el-select v-model='selected_protocol'>
        <el-option
        v-for="(item, idx) in protocols"
        :key='item.label'
        :label='item.label'
        :value='item.value'
        />
      </el-select>
    </os-entry> -->
    <os-select :item="$t('network.wan.proto_label')"
    v-model='selected_protocol' :wholeField="true" :options="protocols">
    </os-select>
    <div v-show="selected_protocol=='dhcp'">
        <os-input v-for="(item, idx) in fields_dhcp"
        :key='idx' :item='item' v-model="value_dhcp[idx]" :tip="dns_tip"></os-input>
        <div class="value alone-right">
          <div class="btn btn-blue" @click="handleSave">{{$t('btn.save')}}</div>
        </div>
    </div>
    <div v-show="selected_protocol=='pppoe'">
      <template v-for="(item, idx) in fields_pppoe">
        <os-input v-if="item.indexOf('dns') > -1 || item.indexOf('DNS') > -1"
        :key='idx' :item='item' v-model="value_pppoe[idx]" :tip="dns_tip"></os-input>
        <os-input v-else
        :key='idx' :item='item' v-model="value_pppoe[idx]"></os-input>
      </template>
      <div class="value alone-right">
        <!-- 按钮换行加入行间距 -->
        <div class="btn btn-blue mb20" @click="pppoe_click0">{{btns[0]}}</div>
        <div class="btn btn-blue mb20" @click="pppoe_click1">{{btns[1]}}</div>
        <div class="btn btn-blue mb20" @click="pppoe_click2">{{btns[2]}}</div>
        <!-- @click 使用closure传参 onclick直接执行函数 -->
        <div class="btn btn-blue mb20" @click="pppoe_click3">{{btns[3]}}</div>
      </div>
    </div>
    <div v-show="selected_protocol=='static'">
      <template v-for="(item, idx) in fields_static">
        <os-input v-if="item.indexOf('dns') > -1 || item.indexOf('DNS') > -1"
        :key='idx' :item='item' v-model="value_static[idx]" :tip="dns_tip"></os-input>
        <os-input v-else
        :key='idx' :item='item' v-model="value_static[idx]"></os-input>
      </template>
      <div class="value alone-right">
        <div class="btn btn-blue" @click="handleSave">{{$t("btn.save")}}</div>
      </div>
    </div>
    <!-- <el-row :gutter="50" class="mb20">
      <el-col :offset="8" :span="16">
        <div class="padding-10">
          <el-button type="primary" size="small" @click='handleSave'>保存</el-button>
        </div>
      </el-col>
    </el-row> -->
    <div class="view-table mb20">
      <div class="table-title">
        {{info.title}}
      </div>
      <table class="table-center">
        <colgroup>
          <col class="w40">
          <col class="w50">
          <col class="w70">
          <col class="w50">
          <col class="w50">
          <col class="w40">
          <col class="w40">
          <col class="w60">
        </colgroup>
        <thead>
          <tr>
            <th v-for="(item, idx) in info.head" :key="idx">{{item}}</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td v-for="(item, idx) in info.value" :key="idx"
            :class="{'text-green': idx==3||idx==5||idx==7,
            'text-orange': idx==4||idx==6 }">{{item}}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="toolbar">{{toolbar}}</div>
    <os-log :title="$t('network.wan.detection')" :log-info="detectionList"></os-log>
  </div>
</template>

<script>
  import { mapGetters, } from 'vuex'
  import _throttle from "lodash/throttle"
  import _debounce from "lodash/debounce"
  import {mydebounce} from "@/utils/public"
  const DURATION = 3000
  export default {
    data(){
      return {
        wan_config: '',
        wan_status: '',
        wan_info: '',
        wan_traffic: '',
        wan_total_traffic: "",
        // 获取流量信息的定时器
        traffic_timer: null,
        // 选择的协议类型
        selected_protocol: '',
        count: 0,
        fields_dhcp: this.$t('network.wan.fields_dhcp'),
        value_dhcp: ['', '', ],
        fields_pppoe: this.$t('network.wan.fields_pppoe'),
        btns: this.$t('network.wan.btns'),
        value_pppoe: ['', '', '', ''],
        fields_static: this.$t('network.wan.fields_static'),
        value_static: ['', '', '', '', ''],
        dns_tip: this.$t("network.wan.dns_tip"),
        input_error_id: false,
        input_error_pwd: false,
        detectionList: [],
        duration: 5000, // timeout
      }
    },
    computed:{
      protocols(){
        return this.$t('network.wan.protocols')
      },
      // 整合表格显示的数据
      info(){
        let data = this.$t('network.wan.info')
        let value = data.value
        let config = this.wan_config
        let traffic = this.wan_status
        let proto = this.value_to_label(this.protocols, traffic.proto)
        value[0] = proto ? proto : '--'
        value[1] = traffic.ipaddr ? traffic.ipaddr : '--'
        value[2] = traffic.macaddr ? traffic.macaddr : '--'
        value[3] = this.formatByte(traffic.tx)
        value[4] = this.formatByte(traffic.rx)
        value[5] = this.formatByte(traffic.txall)   // tx_total
        value[6] = this.formatByte(traffic.rxall)   // rx_total
        value[7] = this.formatDuration(traffic.uptime)  // total time
        // console.log(data.value[1])
        return data
      },
      toolbar(){
        return this.$t('network.wan.toolbar')
      },
      ...mapGetters(['username', 'password']),
    },
    methods: {
      get_wan_config(){
        return this.$req.get('/webapi?op=get_wan_config').then(res=> {

          // 使用解构赋值对 res 解构
          let { data } = res
          console.log(res.data)
          this.selected_protocol = data.proto
          this.value_dhcp.splice(0 , 1, data.dns_primary )
          this.value_dhcp.splice(1 , 1, data.dns_secondary )
          this.value_pppoe.splice(0 , 1, data.username )
          this.value_pppoe.splice(1 , 1, data.password )
          this.value_pppoe.splice(2 , 1, data.dns_primary )
          this.value_pppoe.splice(3 , 1, data.dns_secondary )
          this.value_static.splice(0 , 1, data.ipaddr )
          this.value_static.splice(1 , 1, data.netmask )
          this.value_static.splice(2 , 1, data.gateway )
          this.value_static.splice(3 , 1, data.dns_primary )
          this.value_static.splice(4 , 1, data.dns_secondary )

          this.wan_config = data
        }).finally(()=> {
          console.log("config")
          return Promise.resolve()
        })
      },
      get_wan_status() {
        return this.$req.get("/webapi?op=get_wan_status").then(res=> {
          this.wan_status = res.data
          console.log(this.wan_status)
        }).catch(err=> {}).finally(()=> {
          console.log("status")
          return Promise.resolve()
        })
      },
      handleSave(){
        // TODO 设置wan口协议
        let params;
        console.log(this.wan_config)
        switch(this.selected_protocol){
          case 'pppoe':
            if(!this.isValidIP(...this.filterValue(this.value_pppoe[2], this.value_pppoe[3]))){
              return
            }
            if(this.value_pppoe[0]==""||this.value_pppoe[0]==undefined
            ||this.value_pppoe[1]==""||this.value_pppoe[1]==undefined){
              this.$message({
                type: "error",
                message: this.$t("notification.typeUserPwd"),
                showClose: true,
              })
              return
            }
            params = {
              proto: this.selected_protocol,
              username: this.value_pppoe[0],
              password: this.value_pppoe[1],
              dns_primary: this.value_pppoe[2],
              dns_secondary: this.value_pppoe[3],
            }
            break;
          case 'dhcp':
            console.log(this.value_dhcp[1])
            if(!this.isValidIP(...this.filterValue(this.value_dhcp[0], this.value_dhcp[1]))){
              return
            }
            params = {
              proto: this.selected_protocol,
              dns_primary: this.value_dhcp[0],
              dns_secondary: this.value_dhcp[1],
            }
            break
          case 'static':
            let data = this.deepClone(this.value_static)
            data.splice(1,2)
            if(this.value_static[0]&&this.value_static[1]){

            } else {
              this.$alert(this.$t("notification.ip_or_netmask_empty"), {
                type: "error",
                title: this.$t("notification.notice"),
                showClose: true,
              })
              return
            }
            if(!this.isValidIP(...this.filterValue(...data))){
              return
            }
            params = {
              proto: this.selected_protocol,
              ipaddr: this.value_static[0],
              netmask: this.value_static[1],
              gateway: this.value_static[2],
              dns_primary: this.value_static[3],
              dns_secondary: this.value_static[4],
            }
            break
        }

        console.log(params)
        this.proxy_req("post", "/webapi?op=set_wan_config", params, res=> {
          if(res.code == "1" && params.ipaddr){
            this.wan_config.ipaddr = params.ipaddr
          }
          this.wan_config.proto = params.proto
        }, true, )
      },
      pppoe_click(idx){
        switch(idx){
          case 0:
            this.handleSave()
            break
          case 1:
            console.log("ok")
            this._throttle(()=> this.proxy_req('get', '/webapi?op=pppoe_disconnect',
            {}, res=>{console.log(res, this._throttle)}, true), this.duration)()
            break
          case 2:
            return ()=> this.proxy_req('get', '/webapi?op=pppoe_reconnect', {reconnect: 'reconnect'}, res=>{console.log(res)}, true)
            break
          case 3:
            return ()=> this.proxy_req('get', '/webapi?op=pppoe_detection', {pppoe_detection: 'pppoe_detection'}, res=>{console.log(res)}, true)
            break
        }
      },
      // pppoe_click0: _throttle(this.handleSave, this.duration),
      pppoe_click0: mydebounce(function(){
        // TODO 设置wan口协议
        let params;
        console.log(this.wan_config)
        switch(this.selected_protocol){
          case 'pppoe':
            if(!this.isValidIP(...this.filterValue(this.value_pppoe[2], this.value_pppoe[3]))){
              return
            }
            if(this.value_pppoe[0]==""||this.value_pppoe[0]==undefined
            ||this.value_pppoe[1]==""||this.value_pppoe[1]==undefined){
              this.$message({
                type: "error",
                message: this.$t("notification.typeUserPwd"),
                showClose: true,
              })
              return
            }
            params = {
              proto: this.selected_protocol,
              username: this.value_pppoe[0],
              password: this.value_pppoe[1],
              dns_primary: this.value_pppoe[2],
              dns_secondary: this.value_pppoe[3],
            }
            break;
          case 'dhcp':
            console.log(this.value_dhcp[1])
            if(!this.isValidIP(...this.filterValue(this.value_dhcp[0], this.value_dhcp[1]))){
              return
            }
            params = {
              proto: this.selected_protocol,
              dns_primary: this.value_dhcp[0],
              dns_secondary: this.value_dhcp[1],
            }
            break
          case 'static':
            let data = this.deepClone(this.value_static)
            data.splice(1,2)
            if(!this.isValidIP(...this.filterValue(...data))){
              return
            }
            params = {
              proto: this.selected_protocol,
              ipaddr: this.value_static[0],
              netmask: this.value_static[1],
              gateway: this.value_static[2],
              dns_primary: this.value_static[3],
              dns_secondary: this.value_static[4],
            }
            break
        }

        console.log(params)
        this.proxy_req("post", "/webapi?op=set_wan_config", params, res=> {
          if(res.code == "1"){
            this.count = 0
            // 同步Vuex.Store中的数据
            this.$store.dispatch("info/get_wan")
          }
        }, true, )
      }, DURATION),
      pppoe_click1: mydebounce(function() {
        this.proxy_req('get', '/webapi?op=pppoe_disconnect', {disconnect:"disconnect"}, res=>{console.log(res, this._throttle)}, true)
      }, DURATION),
      pppoe_click2: mydebounce(function() {
        this.proxy_req('get', '/webapi?op=pppoe_reconnect', {reconnect: 'reconnect'}, res=>{console.log(res)}, true)
      }, DURATION),
      // pppoe_click1(idx){
      //   this._throttle(function(){
      //     this.proxy_req('get', '/webapi?op=pppoe_disconnect?disconnect', {}, res=>{console.log(res, this._throttle)}, true)
      //   }, this.duration)()
      // },
      // 只有匿名函数内部才能访问this
      pppoe_click3: mydebounce(function() {
        this.proxy_req('get', '/webapi?op=pppoe_detection', {pppoe_detection: 'pppoe_detection'}, res=>{
          console.log(res)
          this.detectionList = res.data.pppoe_detection.split("\n")
        }, true)
      }, DURATION),
      // 获取wan口信息
      get_wan_info(){
        this.$req.get('/webapi?op=get_wan_info').then(res=> {
          console.log('wan口信息', res)
          this.wan_info = res
        })
      },
    },
    async created(){
      this.$bus.emit('changeTab', 0)
      // Promise.all([this.get_wan_config(), this.get_wan_status()]).then(()=> {
      //   console.log("all")
      //   this.$refs.loading.mounted = true
      // })
      this.get_wan_config()
      this.get_wan_status()
      this.traffic_timer = setInterval(()=> {
        this.get_wan_status()
      }, 2000)
    },
    activated() {
      this.$bus.emit('changeTab', 0)
      console.log('wan action')
      this.traffic_timer = setInterval(()=> {
        this.get_wan_config()
        // this.get_wan_info()
      }, 3000)
    },
    deactivated() {
      clearInterval(this.traffic_timer)
    },
    beforeDestroy(){
      clearInterval(this.traffic_timer)
      console.log("distroyed")
    },
  }
</script>

<style lang="scss" scoped>
  .net-wan{
    .label{
      text-align: right;
      height: 100%;
      justify-content: flex-end;
    }
    .padding-10{
      padding: 10px 0;
    }
    // /deep/ .el-input{
    //   .el-input__inner{
    //     height: 30px;
    //     line-height: 30px;
    //   }
    //   .el-input__icon{
    //     line-height: 30px;
    //   }
    // }
    // /deep/ .el-button{
    //   width: 78px;
    //   height: 26px;
    //   padding: 0 0;
    //   line-height: 26px;
    // }
  }
  @media screen and (max-width: 800px){
    .net-wan{
      .view-table{
        overflow: auto;
      }
      .table-center {
        width: 1024px;
      }
    }
  }
</style>
